// store/index.js
import { createStore } from 'vuex';
import axios from 'axios';  // 添加 axios 导入

export default createStore({
  state: {
    isAuthenticated: false,
    role: null,
    token: null, // 添加 token 到 state
  },

  mutations: {
    setAuth(state, payload) {
      state.isAuthenticated = payload.isAuthenticated;
      state.role = payload.role;
      state.token = payload.token; // 保存 token
      state.info = payload.info; // 保存 info 数据
    }
  },

  actions: {
    async login({ commit }, { userId, password, role }) { // 接收 role 参数
      try {
        // 构建查询参数
        const params = new URLSearchParams({ role }).toString();
        
        // 使用查询参数构造完整 URL
        const response = await axios.post(
          `http://localhost:8080/api/login?${params}`, 
          { userId, password }
        );

        // 提取 JWT 和其他信息
        const token = response.data.data; // JWT 在 response.data.data 中
        const message = response.data.message;

        if (response.data.status === 200 && token) {
          // 附带 token 请求 /info 接口
          const infoResponse = await axios.get('http://localhost:8080/info', {
            headers: {
              Authorization: `Bearer ${token}`
            }
          });

          // 判断 /info 请求是否成功
          if (infoResponse.data.status === 200) {
            // 如果请求成功，根据role跳转 
            commit('setAuth', { isAuthenticated: true, role: role, token: token, info: infoResponse });
            // this.$router.push('/info');
          } else {
            console.error('Info request failed:', infoResponse.statusText);
            alert('Failed to retrieve information');
          }
        } else {
          // 登录失败
          commit('setAuth', { isAuthenticated: false, role: null, token: null });
          console.error('Login failed:', message);
          alert('Login failed');
        }
      } catch (error) {
        console.error('Login failed:', error);
        commit('setAuth', { isAuthenticated: false, role: null, token: null });
        alert('Login failed due to an error');
      }
    },

    async register({ commit }, { username, password }) {
      try {
        const response = await axios.post('http://localhost:8080/api/signup', {
          username,
          password,
        });
        
        if (response.data.success) {
          commit('setAuth', { isAuthenticated: true, role: response.data.role });
        } else {
          console.error('Registration failed:', response.data.message);
          alert('Registration failed');
        }
      } catch (error) {
        console.error('Registration failed:', error);
        alert('Registration failed due to an error');
      }
    },
  }
});
